import React from "react";
import View from "../base/View";
import defaultData from "./data";
import { WeaBrowser, WeaLocaleProvider } from "ecCom";
import { inject, observer } from "mobx-react";
import _ from 'lodash';
import './index.less';
import fillin from '../../../../../apis/fillin';
import { selectType, modeTypes, viewTypes } from '../../../../../constants/form';

const { DESIGN, VIEW } = modeTypes;
const { CURRENT } = selectType;
const { READONLY } = viewTypes;
const getLabel = WeaLocaleProvider.getLabel;
let curMember = {};

@inject('routing')
export default class MultiBrowserHrmView extends View {
  constructor(props) {
    super(props);
    
    this.state = {
      members: []
    }
  }

  componentDidMount() {
    const { data: { type, defaultValue }, modeType, value, viewType, uuid } = this.props;
    const { members } = this.state;

    if (window.fromRouter === 'repair') {
      curMember = {};
    }

    if (modeType !== DESIGN && type === CURRENT) {
      fillin.getCurrUser().then(res => {
        if (viewType === READONLY && (!value || !value.id)) {
          this.setState({ members: [] })
        }else {
          this.setState({ members: [...members, { id: res.id, name: res.name }] })
          this.handleValueChange(res.id);
        }

        if (defaultValue) {
          this.setState({ members: defaultValue })
          !value && this.handleValueChange(defaultValue.map(dv => dv.id).join(","))
        }
        
        if(value === null) {
         this.setState({ members: [] })
        this.handleValueChange(null);
      }

        if (_.isObject(value)) {
          const { id, name } = value;
          if (name && id) {
            const nameArr = name.split(',');
            const tempMembers = id.split(',').map((item, i) => {
              return {
                id: item,
                name: nameArr[i]
              };
            })
            this.setState({ members: tempMembers })
            this.handleValueChange(tempMembers.map(dv => dv.id).join(","))
          }
        }
        if (_.isString(value) && curMember[uuid] && window.fromRouter !== 'repair') {
          this.setState({ members: curMember[uuid] || [] });
          this.handleValueChange(curMember[uuid].map(dv => dv.id).join(","))
        }
      })
    }else {
      if (defaultValue) {
        this.setState({ members: defaultValue })
        !value && this.handleValueChange(defaultValue.map(dv => dv.id).join(","))
      }

      if(value === null) {
         this.setState({ members: [] })
        this.handleValueChange(null);
      }

      if (_.isObject(value)) {
        const { id, name } = value;
        if (name && id) {
          const nameArr = name.split(',');
          const tempMembers = id.split(',').map((item, i) => {
            return {
              id: item,
              name: nameArr[i]
            };
          })
          this.setState({ members: tempMembers })
          this.handleValueChange(tempMembers.map(dv => dv.id).join(","))
        }
      }

      if (_.isString(value) && curMember[uuid] && window.fromRouter !== 'repair') {
        this.setState({ members: curMember[uuid] || [] });
        this.handleValueChange(curMember[uuid].map(dv => dv.id).join(","))
      }
    }
  }

  receiveMessageFromIndex = (event) => {
    const { uuid, routing, shortkey } = this.props;

    if (event != undefined && event.data[uuid]) {
      const { ids, names } = event.data[uuid];

      if (ids) {
        const idsArr = ids.split(',');
        const namesArr = names.split(',');
        const finalArr = [];

        idsArr.forEach((id, index) => {
          finalArr.push({
            id,
            name: namesArr[index]
          })
        })
        if (names) {
          this.setState({ members: finalArr });
          curMember[uuid] = finalArr;
          this.handleValueChange(ids);
          // this.props.routing.history.go(-1);
          routing.history.push({//本地开发模式需改成/edc/formview/${shortkey}
            pathname: `/`,
          })
        }
      } else {
        this.setState({ members: [] });
        curMember[uuid] = [];
        this.handleValueChange('');
        routing.history.push({//本地开发模式需改成/edc/formview/${shortkey}
          pathname: `/`,
        })
      }
    }

    window.removeEventListener("message", this.receiveMessageFromIndex, false);
  }

  componentWillReceiveProps(nextProps) {
    const { data: { defaultValue }, value } = nextProps;
    const { modeType } = this.props;

    modeType === DESIGN && this.setState({ members: defaultValue })
    
    if (modeType !== DESIGN && _.isObject(value)) {
      const { id, name } = value;
      if(id && name) {
        const nameArr = name.split(',');
        const tempMembers = id.split(',').map((item, i) => {
          return {
            id: item,
            name: nameArr[i]
          };
        })
        this.setState({ members: tempMembers })
        this.handleValueChange(tempMembers.map(dv => dv.id).join(","))
      }
    }
  }

  onBrowserChange = (ids, names) => {
    if (ids) {
      const idsArr = ids.split(',');
      const namesArr = names.split(',');
      const finalArr = [];

      idsArr.forEach((id, index) => {
        finalArr.push({
          id,
          name: namesArr[index]
        })
      });
      this.setState({ members: finalArr })
      this.handleValueChange(ids)
    } else {
      this.setState({ members: [] })
      this.handleValueChange('');
    }
  } 

  onBrowerHrmClick = () => {
    const { members } = this.state;
    const { uuid } = this.props;
    const finalValue = members ? encodeURI(JSON.stringify(members)) : '';

    //监听message事件
    window.addEventListener("message", this.receiveMessageFromIndex, false);
    window.fromRouter = 'browser';
    this.props.routing.history.push({
      pathname: 'edc/browserHrm',
      state: {
        finalValue, uuid,
        isSingle: '0'
      }
    });
  }

  renderForPC(data, value) {
    const { members } = this.state;

    return (
      <WeaBrowser ecId={`${this && this.props && this.props.ecId || ''}_WeaBrowser@f9gsue`}
        title={getLabel(516509, '多人力资源')}
        type={1}
        textDecoration={true}
        replaceDatas={members}
        isSingle={false}
        onChange={(ids, names, datas) => this.onBrowserChange(ids, names)}
      />
    );
  }

  renderForMobile(data, value) {
    const { members } = this.state;

    return (//<a target='_blank' href={'spa/hrm/static4mobile/index.html#/resourceInfo/' + id}>{name}</a>
      <div>
        <div className='mobile-browserHrm'>
          <div className='content'>
            <ul>
              {
                members && 
                members.map(({ id, name }) => (
                  <li>
                    <span>{ name }</span>
                  </li>
                ))
              }
            </ul>
          </div>
          <i className='anticon anticon-search' onClick={this.onBrowerHrmClick} />
        </div>
      </div>
    );
  }

  renderForReadonly (data, value) {
    const { members } = this.state;

    return (
      <div>
        <div className='mobile-browserHrm'>
          <div className='content'>
            <ul>
              {
                members &&
                members.map(({ id, name }) => (
                  <li>
                    <span>{name}</span>
                  </li>
                ))
              }
            </ul>
          </div>
        </div>
      </div>
    );
  }
}

MultiBrowserHrmView.defaultProps = {
  data: defaultData,
  value: ''
};